package com.example.bbs.advice;


import com.alibaba.fastjson.JSON;
import com.example.bbs.domain.model.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice(annotations = Controller.class)
@Slf4j
public class ExceptionAdvice {

    @ExceptionHandler(Exception.class)
    public void handlerException(HttpServletRequest request, HttpServletResponse response, Exception e) throws IOException {

        log.error("服务器异常：" + e.getMessage());
        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
            log.error(stackTraceElement.toString());
        }
        if (request.getHeader("x-requested-with") == null) {
            response.sendRedirect(request.getContextPath() + "/error");
        } else {
            response.setContentType("application/plain;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(ResponseResult.failure("服务器异常！")));
            writer.flush();
            writer.close();
        }

    }

    //处理Valid注解的参数校验异常错误信息返回
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ResponseResult paramCheck(BindException e) {
        String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
        return ResponseResult.failure(defaultMessage);
    }



}
